from absl import app, flags
import numpy as np
import pandas as pd

from coin.base.datetime_util import (convert_string_to_dates, iterate_date)
from coin.experimental.xguo.order_and_feed_stats.logic.query_func import (_gen_engine,
                                                                          calculate_spread_bp,
                                                                          query_total_turnover,
                                                                          read_csv_into_df)

FLAGS = flags.FLAGS


def main(_):
  csv_root = FLAGS.csv_root
  assert csv_root, '--csv_root must be specified.'
  start_date = FLAGS.start_date
  assert start_date, '--start_date must be specified.'
  end_date = FLAGS.end_date
  assert end_date, '--end_date must be specified.'
  machine = FLAGS.machine
  assert machine, '--machine must be specified.'

  start_date = convert_string_to_dates(start_date)[0]
  end_date = convert_string_to_dates(end_date)[0]
  trading_dates = [td for td in iterate_date(start_date, end_date)]
  exchange_list = ['Bitfinex', 'Huobi', 'Okex']

  df_rows = []
  turnover_df = pd.DataFrame()
  for exchange in exchange_list:
    turnover_result = query_total_turnover(exchange, start_date, end_date)
    turnover_df = pd.concat([turnover_df, turnover_result])
    for symbol in turnover_result['symbol']:
      spread_bp_list = []
      for trading_date in trading_dates:
        df = read_csv_into_df(csv_root, machine, trading_date, exchange, symbol)
        spread_bp = calculate_spread_bp(df)
        spread_bp_list.append(spread_bp)
      mean_spread_bp = np.mean(spread_bp_list)
      df_rows.append([exchange, symbol, mean_spread_bp])
  mean_spread_bp_df = pd.DataFrame(df_rows, columns=['exchange', 'symbol', 'mean_spread_bp'])
  concated_df = pd.merge(turnover_df, mean_spread_bp_df, on=['exchange', 'symbol'], how='left')
  print(concated_df)

  pd.set_option('display.width', 1000)
  pd.set_option('display.max_columns', None)


if __name__ == "__main__":
  flags.DEFINE_string('csv_root', None, 'Output csv files root directory.')

  flags.DEFINE_string('start_date', None, 'yyyymmdd')

  flags.DEFINE_string('end_date', None, 'yyyymmdd. Feed at end_date is not checked.')

  flags.DEFINE_string('machine', None, 'Instance machine name.')

  app.run(main)
